package com.example.demo.msg.nio;/**
 * Created by kete on 2018-08-10.
 */

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * 作者：kete
 * 创建时间：2018-08-10 16:47
 * 功能描述：
 * 版本：
 */
public class ServerHandle implements Runnable{

    private Selector selector;

    private ServerSocketChannel serverSocketChannel;

    private volatile boolean started;


    public ServerHandle(int port) {
        try {
            selector = Selector.open();
            serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.bind(new InetSocketAddress(port),1024);

            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

            started = true;

            System.out.printf("服务已启动,端口:"+port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (started){
            try {
                selector.select(1000);
                Set<SelectionKey> keys = selector.selectedKeys();

                Iterator<SelectionKey> it = keys.iterator();

                SelectionKey key = null;
                while (it.hasNext()){
                    key = it.next();
                    it.remove();

                    try {
                        handleSelector(key);
                    } catch (Exception e) {
                        e.printStackTrace();
                        if(null != key){
                            key.cancel();
                            if(null != key.channel()){
                                key.channel().close();
                            }
                        }
                    }

                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(null != selector){
            try {
                selector.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public void stop(){
        started = false;
    }

    private void handleSelector(SelectionKey key) throws Exception{
        if(key.isValid()){

            if(key.isAcceptable()){
                ServerSocketChannel channel = (ServerSocketChannel)key.channel();
                SocketChannel sc = channel.accept();
                sc.configureBlocking(false);

                sc.register(selector,SelectionKey.OP_READ);
            }else if(key.isReadable()){
                SocketChannel sc = (SocketChannel)key.channel();
                ByteBuffer bf = ByteBuffer.allocate(1024);

                int readBytes = sc.read(bf);

                if(readBytes>0){

                    bf.flip();
                    byte[] bytes = new byte[bf.remaining()];
                    bf.get(bytes);

                    String exproess = new String(bytes,"utf-8");

                    System.out.printf("服务端收到 消息:"+exproess);

                    byte[] writeBytes = new String("你发送的消息为"+exproess).getBytes("utf-8");

                    ByteBuffer wrBf = ByteBuffer.allocate(writeBytes.length);
                    wrBf.put(writeBytes);

                    wrBf.flip();

                    sc.write(wrBf);


                }else if(readBytes<0){
                    key.cancel();
                    sc.close();
                }

            }

        }

    }
}
